const express = require('express');
const webpack = require('webpack');
const opn = require('opn');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware=require('webpack-hot-middleware')
const path = require('path')
const app = express();
const config = require('./webpack.dev.js');
const mock =require('./mock.js');



const proxyMiddleware = require('http-proxy-middleware')
const port = process.env.PORT || config.devServer.port;
const autoOpenBrowser = !!config.devServer.open;
const proxyTable = config.devServer.proxy;

const compiler = webpack(config);
const devMiddleware = webpackDevMiddleware(compiler, {
    publicPath: config.output.publicPath,
    quiet: true
})
const hotMiddleware = webpackHotMiddleware(compiler, {
    log: false,
    heartbeat: 2000
})


Object.keys(proxyTable).forEach(function (context) {
    let options = proxyTable[context]
    if (typeof options === 'string') {
      options = { target: options }
    }
    app.use(proxyMiddleware(options.filter || context, options))
})
mock(app);
app.use(hotMiddleware);
//app.use(require('connect-history-api-fallback')())
app.use(devMiddleware)
app.use('/static', express.static('./static'));


var portfinder = require('portfinder')
portfinder.basePort = port;
var server;
var _resolve
var _reject
var readyPromise = new Promise((resolve, reject) => {
  _resolve = resolve
  _reject = reject
})

devMiddleware.waitUntilValid(() => {
    portfinder.getPort((err, port) => {
      if (err) {
        _reject(err);
      }
      process.env.PORT = port
      var uri = 'http://localhost:' + port
      console.log('> Listening at ' + uri + '\n')
      // when env is testing, don't need open it
      if (autoOpenBrowser && process.env.NODE_ENV !== 'testing') {
        opn(uri)
      }
      server= app.listen(port)
      _resolve();
    })
});
module.exports = {
    ready: readyPromise,
    close: () => {
      server.close()
    }
}